package cn.fourhundredandeighteen.utill;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @description:
 * @author: liuyongqi
 * @time: 2020/12/14
 */
public class MysqlConnect {
    private static InputStream in;
    private static SqlSessionFactory sqlSessionFactory;
    private static SqlSession sqlSession;

    public static SqlSession into() {
        try {
            in = Resources.getResourceAsStream("mybatis-config.xml");//读取mybatis配置文件
        } catch (IOException e) {
            System.out.println("未找到文件--接口错误请类型管理员");
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);//创建sqlsession工厂
        sqlSession = sqlSessionFactory.openSession(true);//获得sqlsession
        return sqlSession;
    }

    public static void destroy() {
        //吧数据提交到数据库
        sqlSession.commit();
        //关闭流
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //关闭sqlSession
        sqlSession.close();
    }
}
